import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/typings.d';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { FormInstance } from 'antd';
import { message } from 'antd';
import { useRef } from 'react';
import { useModel } from 'umi';
import { updateIotSim } from '../service';
import type { IotSimTableListItem, UpdateIotSimType } from '../typings.d';

const UpdateIotSim = (props: {
  reload: () => void;
  iotSim: IotSimTableListItem;
  visible: boolean;
  setUnvisible: () => void;
}) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const role = currUser?.role;
  const { reload, iotSim, visible, setUnvisible } = props;
  const formRef = useRef<FormInstance>();
  return (
    <ModalForm<UpdateIotSimType>
      title="修改流量卡"
      layout="horizontal"
      width="40vw"
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setUnvisible();
        },
      }}
      formRef={formRef}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      visible={visible}
      initialValues={{
        iccid: iotSim.iccid,
        application: iotSim.application,
        deviceType: iotSim.deviceType,
        ownerId: iotSim.ownerId,
      }}
      onFinish={async (values) => {
        const res = await updateIotSim(iotSim._id, values);
        if (res.success) {
          message.success({ content: res.message, key: 'update_iotSim' });
          reload();
          setUnvisible();
          return true;
        }
        message.error({ content: res.message, key: 'update_iotSim' });
        return false;
      }}
    >
      <ProFormText disabled required label="流量卡号" placeholder="请输入流量卡号" name="iccid" />
      <ProFormSelect
        label="设备类型"
        required
        placeholder="请选择设备类型"
        name="deviceType"
        options={[
          {
            label: '视频巡检车',
            value: 0,
          },
          {
            label: 'GPS设备',
            value: 1,
          },
          {
            label: '4G车位锁',
            value: 2,
          },
          {
            label: '4G流量主机',
            value: 3,
          },
          {
            label: '诱导屏控制卡',
            value: 4,
          },
          {
            label: '其他设备',
            value: 99,
          },
        ]}
      />
      <ProFormTextArea label="备注" name="application" placeholder="请填写本流量卡具体用途" />

      {role === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="归属公司"
          showSearch
          debounceTime={200}
          rules={[{ required: true, message: '请选择流量卡所属' }]}
          placeholder="请选择流量卡所属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords, true)}
        />
      )}
    </ModalForm>
  );
};

export default UpdateIotSim;
